package com.apping.demo.bbs.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import android.util.Log;

public class HttpTools {

	private String content;
	
	public void post(String path, byte[] data) {
		StringBuilder stringBuilder = new StringBuilder();
		HttpURLConnection conn = null;
		try {
			URL url = new URL(path);
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3000);
			conn.setRequestProperty("content-length", String.valueOf(data.length));  
			conn.setRequestProperty("content-type","application/x-www-form-urlencoded"); 
			conn.setDoOutput(true);
			//conn.setDoInput(true);
			OutputStream out = conn.getOutputStream();
			out.write(data, 0, data.length);
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
			}
			
			this.content = stringBuilder.toString();
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			conn.disconnect();
		}
	}

	public void post2(String path, String data) throws Exception {
		StringBuilder stringBuilder = new StringBuilder();

		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type", "application/json");
		conn.connect();

		PrintWriter out = new PrintWriter(conn.getOutputStream());
		out.print(data);

		out.flush();
		out.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line);
		}
		
		this.content = stringBuilder.toString();
		reader.close();
	}

	public void get(String path) throws Exception {
		StringBuilder stringBuilder = new StringBuilder();

		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5*1000);
		conn.setRequestMethod("GET");
		
		conn.connect();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			stringBuilder.append(line);
		}

		this.content = stringBuilder.toString();
		reader.close();
	}

	public String getContent() {
		return this.content;
	}
}
